document.addEventListener('DOMContentLoaded', function() {
    console.log("健康证管理页面已加载");
    
    // 获取DOM元素
    const healthCardListBody = document.getElementById('healthCardListBody');
    const emptyMessage = document.getElementById('emptyMessage');
    const selectAllCheckbox = document.getElementById('selectAll');
    const selectAllBtn = document.getElementById('selectAllBtn');
    const deselectAllBtn = document.getElementById('deselectAllBtn');
    const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
    const selectedCountSpan = document.getElementById('selectedCount');
    const confirmDialog = document.getElementById('confirmDialog');
    const confirmMessage = document.getElementById('confirmMessage');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
    
    // 搜索相关元素
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const clearSearchBtn = document.getElementById('clearSearchBtn');
    
    // 添加刷新按钮
    const refreshBtn = document.createElement('button');
    refreshBtn.id = 'refreshBtn';
    refreshBtn.className = 'action-btn view-btn';
    refreshBtn.textContent = '刷新';
    searchBtn.parentNode.insertBefore(refreshBtn, clearSearchBtn);
    
    // 存储原始数据
    let allHealthCards = [];
    
    // 当前待删除的健康证ID
    let currentDeleteTarget = null;
    let selectedIds = [];
    
    // 格式化日期函数
    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
    
    // 显示加载中提示
    function showLoading() {
        healthCardListBody.innerHTML = '<tr><td colspan="4" style="text-align:center;">加载中，请稍候...</td></tr>';
        emptyMessage.style.display = 'none';
    }
    
    // 显示错误提示
    function showError(message) {
        healthCardListBody.innerHTML = `<tr><td colspan="4" style="text-align:center;color:red;">${message}</td></tr>`;
        emptyMessage.style.display = 'none';
    }
    
    // 显示消息提示
    function showMessage(message, isSuccess) {
        // 检查是否存在消息容器，如果不存在则创建一个
        let messageContainer = document.getElementById('messageContainer');
        if (!messageContainer) {
            messageContainer = document.createElement('div');
            messageContainer.id = 'messageContainer';
            document.body.appendChild(messageContainer);
        }
        
        // 创建消息元素
        const messageElement = document.createElement('div');
        messageElement.className = isSuccess ? 'message-success' : 'message-error';
        messageElement.classList.add('page-message');
        messageElement.textContent = message;
        
        // 添加到容器中
        messageContainer.appendChild(messageElement);
        
        // 设置淡入效果
        setTimeout(() => {
            messageElement.style.opacity = '1';
        }, 10);
        
        // 设置自动消失
        setTimeout(() => {
            messageElement.style.opacity = '0';
            setTimeout(() => {
                if (messageElement.parentNode === messageContainer) {
                    messageContainer.removeChild(messageElement);
                }
            }, 300);
        }, 3000);
    }
    
    // 加载健康证列表
    async function loadHealthCardList() {
        console.log("开始加载健康证列表");
        showLoading();
        
        // 优先从数据库加载数据
        if (window.healthCardApi) {
            try {
                console.log("尝试从数据库加载健康证列表...");
                const result = await window.healthCardApi.getCardIndex();
                
                if (result && !result.error) {
                    console.log("从数据库成功获取健康证索引");
                    
                    // 检查返回数据是否为空
                    if (Object.keys(result).length === 0) {
                        console.log("数据库中没有健康证记录");
                        healthCardListBody.innerHTML = '';
                        emptyMessage.style.display = 'block';
                        emptyMessage.textContent = '暂无健康证记录';
                        return;
                    }
                    
                    // 隐藏空列表提示
                    emptyMessage.style.display = 'none';
                    
                    // 将数据库结果转换为前端所需格式
                    const keys = Object.keys(result);
                    const sortedEntries = keys
                        .map(key => ({ id: key, data: result[key] }))
                        .sort((a, b) => {
                            // 尝试按创建时间排序，如果没有则按uniqueId排序
                            const dateA = a.data.createTime ? new Date(a.data.createTime) : new Date(0);
                            const dateB = b.data.createTime ? new Date(b.data.createTime) : new Date(0);
                            return dateB - dateA;
                        });
                    
                    // 保存所有数据用于搜索
                    allHealthCards = sortedEntries;
                    
                    // 渲染列表
                    renderHealthCardList(sortedEntries);
                    console.log("从数据库加载的健康证记录数:", sortedEntries.length);
                    return;
                } else {
                    console.error("从数据库获取健康证索引失败:", result?.error);
                }
            } catch (error) {
                console.error("从数据库加载健康证列表出错:", error);
                // 不再显示详细错误，只显示简单消息
                showError('数据库连接失败，尝试从本地存储加载');
            }
        }
        
        // 如果数据库加载失败，尝试从localStorage加载（降级方案）
        console.log("尝试从localStorage加载健康证列表...");
        const healthCardIndex = localStorage.getItem('healthCardIndex');
        
        if (!healthCardIndex) {
            console.log("未找到健康证索引");
            healthCardListBody.innerHTML = '';
            emptyMessage.style.display = 'block';
            emptyMessage.textContent = '暂无健康证记录 (localStorage)';
            return;
        }
        
        try {
            const indexData = JSON.parse(healthCardIndex);
            const keys = Object.keys(indexData);
            
            if (keys.length === 0) {
                console.log("健康证索引为空");
                healthCardListBody.innerHTML = '';
                emptyMessage.style.display = 'block';
                return;
            }
            
            // 隐藏空列表提示
            emptyMessage.style.display = 'none';
            
            // 按创建时间排序（最新的在前面）
            const sortedEntries = keys
                .map(key => ({ id: key, data: indexData[key] }))
                .sort((a, b) => {
                    const dateA = new Date(a.data.createTime || 0);
                    const dateB = new Date(b.data.createTime || 0);
                    return dateB - dateA;
                });
            
            // 保存所有数据用于搜索
            allHealthCards = sortedEntries;
            
            // 渲染列表
            renderHealthCardList(sortedEntries);
            console.log("从localStorage加载的健康证记录数:", sortedEntries.length);
            
        } catch (error) {
            console.error("加载健康证列表失败:", error);
            showError('加载健康证列表失败');
        }
    }
    
    // 渲染健康证列表
    function renderHealthCardList(entries) {
        if (!entries || entries.length === 0) {
            healthCardListBody.innerHTML = '';
            emptyMessage.style.display = 'block';
            return;
        }
        
        // 隐藏空列表提示
        emptyMessage.style.display = 'none';
        
        // 生成列表HTML
        let html = '';
        entries.forEach(entry => {
            const card = entry.data;
            html += `
                <tr data-id="${entry.id}">
                    <td><input type="checkbox" class="card-checkbox" data-id="${entry.id}"></td>
                    <td>${card.name || 'N/A'}</td>
                    <td>${card.id || 'N/A'}</td>
                    <td>
                        <button class="action-btn view-btn view-card" data-id="${entry.id}">查看</button>
                    </td>
                </tr>
            `;
        });
        
        healthCardListBody.innerHTML = html;
        console.log("健康证列表渲染完成，条目数:", entries.length);
        
        // 添加事件监听器
        addEventListeners();
    }
    
    // 搜索健康证
    function searchHealthCards(keyword) {
        if (!keyword || keyword.trim() === '') {
            return allHealthCards;
        }
        
        keyword = keyword.trim().toLowerCase();
        
        return allHealthCards.filter(entry => {
            const card = entry.data;
            const nameMatch = (card.name || '').toLowerCase().includes(keyword);
            const idMatch = (card.id || '').toLowerCase().includes(keyword);
            return nameMatch || idMatch;
        });
    }
    
    // 添加事件监听器
    function addEventListeners() {
        // 查看按钮点击事件
        document.querySelectorAll('.view-card').forEach(button => {
            button.addEventListener('click', function() {
                const cardId = this.getAttribute('data-id');
                window.location.href = `preview.html?id=${cardId}`;
            });
        });
        
        // 复选框选择事件
        document.querySelectorAll('.card-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', updateSelectedCount);
        });
    }
    
    // 更新选中数量
    function updateSelectedCount() {
        const checkboxes = document.querySelectorAll('.card-checkbox:not(#selectAll)');
        const checkedBoxes = document.querySelectorAll('.card-checkbox:checked:not(#selectAll)');
        
        selectedIds = Array.from(checkedBoxes).map(cb => cb.getAttribute('data-id'));
        selectedCountSpan.textContent = `已选择: ${checkedBoxes.length}`;
        
        // 更新全选复选框状态
        selectAllCheckbox.checked = checkboxes.length > 0 && checkedBoxes.length === checkboxes.length;
    }
    
    // 搜索按钮点击事件
    searchBtn.addEventListener('click', function() {
        const keyword = searchInput.value;
        const searchResults = searchHealthCards(keyword);
        renderHealthCardList(searchResults);
        
        if (searchResults.length === 0) {
            emptyMessage.textContent = '没有找到匹配的健康证记录';
            emptyMessage.style.display = 'block';
        } else {
            console.log(`搜索成功，找到 ${searchResults.length} 条记录`);
        }
    });
    
    // 回车键触发搜索
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchBtn.click();
        }
    });
    
    // 清除搜索按钮点击事件
    clearSearchBtn.addEventListener('click', function() {
        searchInput.value = '';
        renderHealthCardList(allHealthCards);
        emptyMessage.textContent = '暂无健康证记录';
    });
    
    // 删除健康证
    async function deleteHealthCard(cardId) {
        console.log("删除健康证:", cardId);
        
        // 尝试从数据库删除
        if (window.healthCardApi) {
            try {
                console.log("尝试从数据库删除健康证...");
                const result = await window.healthCardApi.deleteCard(cardId);
                
                if (result && !result.error) {
                    console.log("从数据库成功删除健康证");
                    
                    // 同时也从localStorage中清除（冗余清理）
                    try {
                        const healthCardIndex = localStorage.getItem('healthCardIndex');
                        if (healthCardIndex) {
                            const indexData = JSON.parse(healthCardIndex);
                            if (indexData[cardId]) {
                                delete indexData[cardId];
                                localStorage.setItem('healthCardIndex', JSON.stringify(indexData));
                            }
                        }
                        localStorage.removeItem(`healthCard_${cardId}`);
                    } catch (e) {
                        console.error("清理localStorage失败:", e);
                    }
                    
                    return true;
                } else {
                    console.error("从数据库删除健康证失败:", result?.error);
                    // 如果数据库删除失败，回退到localStorage删除
                    return deleteFromLocalStorage(cardId);
                }
            } catch (error) {
                console.error("从数据库删除健康证出错:", error);
                return deleteFromLocalStorage(cardId);
            }
        } else {
            // 如果没有API，直接从localStorage删除
            return deleteFromLocalStorage(cardId);
        }
    }

    // 从localStorage删除健康证（作为回退方法）
    function deleteFromLocalStorage(cardId) {
        try {
            // 从索引中删除
            const healthCardIndex = localStorage.getItem('healthCardIndex');
            
            if (healthCardIndex) {
                const indexData = JSON.parse(healthCardIndex);
                if (indexData[cardId]) {
                    delete indexData[cardId];
                    localStorage.setItem('healthCardIndex', JSON.stringify(indexData));
                }
            }
            
            // 从单独存储中删除
            localStorage.removeItem(`healthCard_${cardId}`);
            
            console.log("健康证从localStorage删除成功");
            return true;
        } catch (error) {
            console.error("从localStorage删除健康证失败:", error);
            return false;
        }
    }
    
    // 全选复选框事件
    selectAllCheckbox.addEventListener('change', function() {
        const isChecked = this.checked;
        document.querySelectorAll('.card-checkbox:not(#selectAll)').forEach(checkbox => {
            checkbox.checked = isChecked;
        });
        updateSelectedCount();
    });
    
    // 全选按钮事件
    selectAllBtn.addEventListener('click', function() {
        document.querySelectorAll('.card-checkbox:not(#selectAll)').forEach(checkbox => {
            checkbox.checked = true;
        });
        selectAllCheckbox.checked = true;
        updateSelectedCount();
    });
    
    // 取消选择按钮事件
    deselectAllBtn.addEventListener('click', function() {
        document.querySelectorAll('.card-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });
        updateSelectedCount();
    });
    
    // 删除选中按钮事件
    deleteSelectedBtn.addEventListener('click', function() {
        const selectedBoxes = document.querySelectorAll('.card-checkbox:checked:not(#selectAll)');
        const count = selectedBoxes.length;
        
        if (count === 0) {
            // 替换alert为页面内提示
            showMessage('请先选择要删除的健康证', false);
            return;
        }
        
        // 更新确认对话框消息
        confirmMessage.textContent = `确定要删除已选择的 ${count} 条健康证记录吗？此操作不可恢复。`;
        
        // 设置当前删除模式为批量删除
        currentDeleteTarget = 'batch';
        
        // 显示确认对话框
        confirmDialog.style.display = 'flex';
    });
    
    // 确认删除按钮事件
    confirmDeleteBtn.addEventListener('click', async function() {
        if (currentDeleteTarget === 'batch') {
            // 批量删除
            let successCount = 0;
            
            // 如果有数据库API，尝试使用批量删除API
            if (window.healthCardApi && selectedIds.length > 0) {
                try {
                    console.log("尝试从数据库批量删除健康证...");
                    const result = await window.healthCardApi.deleteMultipleCards(selectedIds);
                    
                    if (result && !result.error) {
                        console.log("从数据库成功批量删除健康证:", result);
                        successCount = result.deletedCount || selectedIds.length;
                        
                        // 同时从localStorage中清除
                        try {
                            selectedIds.forEach(id => {
                                try {
                                    const healthCardIndex = localStorage.getItem('healthCardIndex');
                                    if (healthCardIndex) {
                                        const indexData = JSON.parse(healthCardIndex);
                                        if (indexData[id]) {
                                            delete indexData[id];
                                        }
                                        localStorage.setItem('healthCardIndex', JSON.stringify(indexData));
                                    }
                                    localStorage.removeItem(`healthCard_${id}`);
                                } catch (e) {
                                    console.error(`清理localStorage中的${id}失败:`, e);
                                }
                            });
                        } catch (e) {
                            console.error("批量清理localStorage失败:", e);
                        }
                    } else {
                        console.error("从数据库批量删除健康证失败:", result?.error);
                        // 如果批量删除失败，尝试逐个删除
                        for (const id of selectedIds) {
                            if (await deleteHealthCard(id)) {
                                successCount++;
                            }
                        }
                    }
                } catch (error) {
                    console.error("从数据库批量删除健康证出错:", error);
                    // 回退到逐个删除
                    for (const id of selectedIds) {
                        if (await deleteHealthCard(id)) {
                            successCount++;
                        }
                    }
                }
            } else {
                // 没有API或没有选中的ID，逐个删除
                for (const id of selectedIds) {
                    if (await deleteHealthCard(id)) {
                        successCount++;
                    }
                }
            }
            
            // 重新加载列表
            loadHealthCardList();
            
            // 显示结果
            if (successCount > 0) {
                // 替换alert为页面内提示
                showMessage(`成功删除 ${successCount} 条健康证记录`, true);
            } else {
                // 替换alert为页面内提示
                showMessage('删除失败，请重试', false);
            }
        } else if (currentDeleteTarget) {
            // 单个删除
            if (await deleteHealthCard(currentDeleteTarget)) {
                // 直接从DOM中移除行
                const row = document.querySelector(`tr[data-id="${currentDeleteTarget}"]`);
                if (row) row.remove();
                
                // 检查是否为空列表
                if (healthCardListBody.children.length === 0) {
                    emptyMessage.style.display = 'block';
                }
                
                // 从allHealthCards中也移除
                allHealthCards = allHealthCards.filter(card => card.id !== currentDeleteTarget);
            } else {
                // 替换alert为页面内提示
                showMessage('删除失败，请重试', false);
            }
        }
        
        // 重置并隐藏对话框
        currentDeleteTarget = null;
        selectedIds = [];
        confirmDialog.style.display = 'none';
        updateSelectedCount();
    });
    
    // 取消删除按钮事件
    cancelDeleteBtn.addEventListener('click', function() {
        confirmDialog.style.display = 'none';
        currentDeleteTarget = null;
    });
    
    // 点击对话框外部关闭
    confirmDialog.addEventListener('click', function(e) {
        if (e.target === confirmDialog) {
            confirmDialog.style.display = 'none';
            currentDeleteTarget = null;
        }
    });
    
    // 刷新按钮点击事件
    refreshBtn.addEventListener('click', function() {
        console.log("刷新健康证列表");
        loadHealthCardList();
    });
    
    // 初始化加载健康证列表
    loadHealthCardList();
}); 